﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Web;
using System.Web.Script.Serialization;

namespace WxInternet
{
    public class HttpRequestManager
    {
        private HttpRequestManager()
        {
        }
        private static HttpRequestManager _instance = new HttpRequestManager();
        public static HttpRequestManager Instance
        {
            get
            {
                if (_instance == null)
                {
                    _instance = new HttpRequestManager();
                }
                return _instance;
            }
        }
        public T JsonDeserialize<T>(string input)
        {
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            return serializer.Deserialize<T>(input);
        }

        public string JsonGetValueByKey(string jsonStr)
        {
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            var dic = serializer.Deserialize<Dictionary<object, object>>(jsonStr);
            var value = dic["data"].ToString();
            return value;
        }
        public string GetTimeStamp()
        {
            TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
            return Convert.ToInt64(ts.TotalSeconds).ToString();
        }

      

        public string RequestGet(string url)
        {
            string serviceAddress = url;
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(serviceAddress);
            request.Method = "GET";
            request.ContentType = " text/html; charset=utf-8";
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream myResponseStream = response.GetResponseStream();
            StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.UTF8);
            string retString = myStreamReader.ReadToEnd();
            myStreamReader.Close();
            myResponseStream.Close();
            return retString;
        }

      

      
        public string RequestForPost(string url)
        {
            string strResult = "";
            try
            {
                HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(url);
                myRequest.Method = "POST";
                myRequest.ContentType = "application/x-www-form-urlencoded";
                try
                {
                    HttpWebResponse HttpWResp = (HttpWebResponse)myRequest.GetResponse();
                    Stream myStream = HttpWResp.GetResponseStream();
                    StreamReader sr = new StreamReader(myStream, Encoding.UTF8);
                    StringBuilder strBuilder = new StringBuilder();
                    while (-1 != sr.Peek())
                    {
                        strBuilder.Append(sr.ReadLine());
                    }
                    strResult = strBuilder.ToString();
                }
                catch (Exception exp)
                {
                    strResult = "错误：" + exp.Message;
                }
            }
            catch (Exception exp)
            {
                strResult = "错误：" + exp.Message;
            }
            return strResult;
        }

        #region 加密与解密
        const string KEY_64 = "JocceApp";//注意了，是8个字符，64位

        const string IV_64 = "JocceApp";

        /// <summary>
        /// 加密
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public string Encode(string data)//加密
        {
            byte[] byKey = System.Text.ASCIIEncoding.ASCII.GetBytes(KEY_64);
            byte[] byIV = System.Text.ASCIIEncoding.ASCII.GetBytes(IV_64);

            DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider();
            int i = cryptoProvider.KeySize;
            MemoryStream ms = new MemoryStream();
            CryptoStream cst = new CryptoStream(ms, cryptoProvider.CreateEncryptor(byKey, byIV), CryptoStreamMode.Write);

            StreamWriter sw = new StreamWriter(cst);
            sw.Write(data);
            sw.Flush();
            cst.FlushFinalBlock();
            sw.Flush();
            return Convert.ToBase64String(ms.GetBuffer(), 0, (int)ms.Length);

        }
        /// <summary>
        /// 解密
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public string Decode(string data)//解密
        {
            var result = "未知";
            try
            {
                byte[] byKey = System.Text.ASCIIEncoding.ASCII.GetBytes(KEY_64);
                byte[] byIV = System.Text.ASCIIEncoding.ASCII.GetBytes(IV_64);

                byte[] byEnc;
                try
                {
                    byEnc = Convert.FromBase64String(data);
                }
                catch
                {
                    return null;
                }

                DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider();
                MemoryStream ms = new MemoryStream(byEnc);
                CryptoStream cst = new CryptoStream(ms, cryptoProvider.CreateDecryptor(byKey, byIV), CryptoStreamMode.Read);
                StreamReader sr = new StreamReader(cst);

                result = sr.ReadToEnd();
            }
            catch (Exception ex)
            {


            }
            return result;
        }
        #endregion

        /// <summary>
        /// 获取请求者的ip
        /// </summary>
        /// <returns></returns>
        public string IpAddress()
        {
            string strIpAddress = "";
            try
            {
                strIpAddress = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
                if (strIpAddress == null)
                {
                    strIpAddress = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
                }
            }
            catch
            { }
            if (!strIpAddress.Equals(""))
            {
                strIpAddress = strIpAddress.Replace(",", "").Replace("121.41.160.210", "");
            }
            return strIpAddress;
        }

        /// <summary>
        /// 转换字节流并调用方法
        /// </summary>
        /// <param name="data"></param>
        /// <param name="url"></param>
        /// <returns></returns>
        public string PostDataToUrl(string data, string url)
        {
            Encoding encoding = Encoding.GetEncoding("utf-8");

            byte[] bytesToPost = encoding.GetBytes(data);

            return PostDataToUrl(bytesToPost, url);
        }


        /// <summary>
        /// 执行链接得到返回信息
        /// </summary>
        /// <param name="data"></param>
        /// <param name="url"></param>
        /// <returns></returns>
        private string PostDataToUrl(byte[] data, string url)
        {
            string stringResponse = string.Empty;

            ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
            #region 创建httpWebRequest对象
            WebRequest webRequest = WebRequest.Create(url);
            HttpWebRequest httpRequest = webRequest as HttpWebRequest;
            #endregion

            #region 填充httpWebRequest的基本信息
            httpRequest.ContentType = "application/x-www-form-urlencoded";
            httpRequest.Method = "POST";
            httpRequest.Timeout = 1000 * 10;

            #endregion


            Stream requestStream = null;
            try
            {
                #region 填充要post的内容
                httpRequest.ContentLength = data.Length;
                requestStream = httpRequest.GetRequestStream();
                requestStream.Write(data, 0, data.Length);
                requestStream.Close();
                #endregion

                #region 发送post请求到服务器并读取服务器返回信息
                Stream responseStream = null;

                try
                {
                    responseStream = httpRequest.GetResponse().GetResponseStream();

                    using (StreamReader responseReader =
                        new StreamReader(responseStream, Encoding.GetEncoding("utf-8")))
                    {
                        stringResponse = responseReader.ReadToEnd();
                    }
                    responseStream.Close();
                }
                catch (Exception e)
                {
                    stringResponse = e.Message;
                }
                #endregion

                #region 读取服务器返回信息

                #endregion
            }
            catch { }
            return stringResponse;
        }

        private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
        {
            return true; //总是接受     
        }

        /// <summary>
        /// 检测xss注入风险
        /// </summary>
        /// <param name="Request"></param>
        /// <returns></returns>
        public bool isxss(HttpRequest Request)
        {
            String parastr = Request.QueryString.ToString().ToLower();

            // 长度为0的返回false
            if (parastr.Length == 0)
            {
                return false;
            }


            // 判断是否有<>
            if (parastr.IndexOf("%3c") >= 0 || parastr.IndexOf("%3e") >= 0 || parastr.IndexOf(">") >= 0 || parastr.IndexOf("<") >= 0 || parastr.IndexOf("onmouse") >= 0 || parastr.IndexOf("'") >= 0 || parastr.IndexOf("%22") >= 0 || parastr.IndexOf("\"") >= 0)
            {
                // 检测到存在有风险字符返回true
                return true;
            }

            return false;

        }
    }
}